package com.heatup.apt.common.dao.redis;

import java.io.Serializable;

import com.heatup.apt.common.util.SerializeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;

public class BaseRedisDao<T> {
	
	@Autowired
	private RedisTemplate<Serializable, Serializable> redisTemplate;
	private long token_vaild_time=1800;
	
	public long getToken_vaild_time() {
		return token_vaild_time;
	}

	public void setToken_vaild_time(long token_vaild_time) {
		this.token_vaild_time = token_vaild_time;
	}

	public BaseRedisDao(){
		
	}
	
	public BaseRedisDao (RedisTemplate<Serializable, Serializable> redisTemplate){
		this.redisTemplate = redisTemplate;
	}
	
	/**
	 * 按KEY-VALUE模式存入对象到redis ,设置过期时间为1800S
	 * @param key
	 * @param value
	 */
	public void save(final String key, Object value) {
		final byte[] vbytes = SerializeUtil.serialize(value);
		redisTemplate.execute(new RedisCallback<Object>() {
			@Override
			public Object doInRedis(RedisConnection connection)
					throws DataAccessException {
				connection.set(redisTemplate.getStringSerializer().serialize(key), vbytes);
				return null;
			}
		});
		this.exprie(key, getToken_vaild_time());
	}
	
	/**
	 * 按KEY设置过期时间
	 * @param key
	 * @param timeSec 多少秒
	 */
	public void exprie(final String key,final long timeSec){
		redisTemplate.execute(new RedisCallback<T>() {
			@Override
			public T doInRedis(RedisConnection connection) throws DataAccessException {
				byte[] keybytes = redisTemplate.getStringSerializer().serialize(key);
				if(connection.exists(keybytes)){
					connection.expire(keybytes, timeSec);	
				}
				return null;
			}
		});
	}
	
	/**
	 * 根据KEY从redis获取数据
	 * @param key
	 * @param elementType
	 * @return
	 */
	public  T get(final String key, Class<T> elementType) {
		return redisTemplate.execute(new RedisCallback<T>() {
			@Override
			public T doInRedis(RedisConnection connection)
					throws DataAccessException {
				byte[] keybytes = redisTemplate.getStringSerializer().serialize(key);
				if (connection.exists(keybytes)) {
					byte[] valuebytes = connection.get(keybytes);
					@SuppressWarnings("unchecked")
					T value = (T) SerializeUtil.unserialize(valuebytes);
					return value;
				}
				return null;
			}
		});
	}
	
	
}
